package com.taobaolite.history;

import com.taobaolite.user.User;
import com.taobaolite.user.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;

import javax.persistence.Table;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class HistoryService {
    private final HistoryRepository historyRepo;
    private final UserRepository userRepo;

    @Autowired
    public HistoryService(HistoryRepository historyRepo, UserRepository userRepo) {
        this.historyRepo = historyRepo;
        this.userRepo = userRepo;
    }

    public List<HistoryBody> getHistory(Long guestId) {
        List<History> historyList= historyRepo.findByGuestId(guestId);
        List<HistoryBody> historyBodyList = new ArrayList<>();

        for (History h : historyList) {
            HistoryBody historyBody = new HistoryBody(
                    h.getItem().getItemId(),
                    h.getHistoryPK().getTime(),
                    h.getItem().getName(),
                    h.getItem().getPrice(),
                    h.getItem().getDescription(),
                    h.getItem().getImageDir(),
                    h.getItem().getStore().getStoreId(),
                    h.getItem().getAmount()
            );
            historyBodyList.add(historyBody);
        }

        return historyBodyList;
    }

    @Transactional
    public void deleteHistory(Long userId, Timestamp time) {
//        User user = userRepo.findById(userId)
//                        .orElseThrow(() -> new ResponseStatusException(
//                                HttpStatus.NOT_FOUND,
//                                "User with ID " + userId +
//                                        " does not exist."
//                        ));
//
//        History history = historyRepo.findById(new HistoryPK(
//                user,
//                time
//        ))
//                .orElseThrow(() -> new ResponseStatusException(
//                        HttpStatus.NOT_FOUND,
//                        "History for user " + userId + " at "
//                        + time + " does not exist."
//                ));

        List<History> historyList= historyRepo.findByGuestId(userId);

        for (History h : historyList) {
            if (Objects.equals(h.getHistoryPK().getTime(), time)) {
                h.setDeleted(true);
                return;
            }
        }

        throw new ResponseStatusException(
                HttpStatus.NOT_FOUND,
                "History for user " + userId + " at "
                        + time + " does not exist."
        );
    }
}
